<script lang="ts">
	import { Any } from '$lib/api/proto/google/protobuf/any';
	import { TrueOrFalseAnswer, TrueOrFalseQuestion } from '$lib/api/proto/resource_exam_type_api';
	import { appStore } from '$lib/stores/app.svelte';
	import { userStore } from '$lib/stores/user.svelte';
	import { callApi } from '$lib/utils/call_utils';
	import { roadmapStore } from '../../store.svelte';

	interface Props {
		questionId: string;
		question: Any;
		answer: Any;
	}
	let props: Props = $props();

	const question = $derived(Any.unpack(props.question, TrueOrFalseQuestion));

	let answer = $state(
		props.answer.typeUrl.endsWith('.TrueOrFalseAnswer')
			? Any.unpack(props.answer, TrueOrFalseAnswer).answer
			: false
	);

	async function setAnswer() {
		if (userStore.userSession == null || roadmapStore.selectNodeIdList.length == 0) {
			return;
		}
		await callApi(
			appStore.resourceExamApiClient.setStateByRoadmap({
				sessionId: userStore.userSession,
				roadmapId: roadmapStore.roadmapId,
				nodeId: roadmapStore.selectNodeIdList[0],
				questionId: props.questionId,
				answer: Any.pack(
					{
						answer: answer
					},
					TrueOrFalseAnswer
				)
			}).response
		);
		roadmapStore.resourceStateVersion += 1;
	}

	$effect(() => {
		answer = props.answer.typeUrl.endsWith('')
			? Any.unpack(props.answer, TrueOrFalseAnswer).answer
			: false;
	});
</script>

<div class="prose max-w-none p-2 w-full">
	<h3>问题:{question.question}</h3>
	<div class="flex gap-2">
		<input
			type="radio"
			name={props.questionId}
			class="radio"
			disabled={roadmapStore.roadmapMode == 'view'}
			checked={answer}
			onchange={(e) => {
				if (e.currentTarget.checked) {
					answer = true;
					setAnswer();
				}
			}}
		/>
		正确
		<input
			type="radio"
			name={props.questionId}
			class="radio"
			disabled={roadmapStore.roadmapMode == 'view'}
			checked={!answer}
			onchange={(e) => {
				if (e.currentTarget.checked) {
					answer = false;
					setAnswer();
				}
			}}
		/>
		错误
	</div>
	{#if roadmapStore.roadmapMode == 'view'}
		<h4>正确答案:&nbsp;{question.rightAnswer ? '正确' : '错误'}</h4>
	{/if}
</div>
